<template>
  <view class="container">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-box">
        <text class="status">{{ orderStatusText }}</text>
        <text class="desc">{{ orderStatusDesc }}</text>
      </view>
    </view>

    <!-- 收货地址 -->
    <view class="address-section">
      <view class="user">
        <text class="name">{{ orderInfo.receiverName }}</text>
        <text class="phone">{{ orderInfo.phoneNumber }}</text>
      </view>
      <view class="address">
        {{ `${orderInfo.province}${orderInfo.city}${orderInfo.district}${orderInfo.detailAddress}` }}
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-section">
      <view 
        class="goods-item" 
        v-for="item in orderInfo.items" 
        :key="item.id"
        @tap="navToGoodsDetail(item.spuId)"
      >
        <image :src="item.primaryImage" mode="aspectFill" class="goods-image" />
        <view class="goods-info">
          <text class="goods-name">{{ item.title }}</text>
          <text class="goods-specs">{{ item.specs }}</text>
          <view class="price-box">
            <text class="price">¥{{ item.salePrice }}</text>
            <text class="count">x{{ item.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-section">
      <view class="item">
        <text>订单编号</text>
        <text class="value">{{ orderInfo.orderNo }}</text>
      </view>
      <view class="item">
        <text>下单时间</text>
        <text class="value">{{ orderInfo.createTime }}</text>
      </view>
      <view class="item">
        <text>支付方式</text>
        <text class="value">{{ orderInfo.paymentMethod }}</text>
      </view>
      <view class="item">
        <text>商品总价</text>
        <text class="price">¥{{ orderInfo.totalAmount }}</text>
      </view>
      <view class="item">
        <text>运费</text>
        <text class="price">¥{{ orderInfo.freight }}</text>
      </view>
      <view class="item">
        <text>优惠金额</text>
        <text class="price">-¥{{ orderInfo.discountAmount }}</text>
      </view>
      <view class="item total">
        <text>实付金额</text>
        <text class="price">¥{{ orderInfo.payAmount }}</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer">
      <block v-if="orderInfo.status === 'unpaid'">
        <button class="btn outline" @tap="cancelOrder">取消订单</button>
        <button class="btn primary" @tap="payOrder">立即支付</button>
      </block>
      <block v-else-if="orderInfo.status === 'unreceived'">
        <button class="btn outline" @tap="viewLogistics">查看物流</button>
        <button class="btn primary" @tap="confirmReceive">确认收货</button>
      </block>
      <block v-else-if="orderInfo.status === 'completed'">
        <button class="btn outline" @tap="deleteOrder">删除订单</button>
        <button class="btn primary" @tap="buyAgain">再次购买</button>
      </block>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { orderService } from '@/services/order';
import { payService } from '@/services/pay';

// 响应式数据
const orderInfo = ref({});

// 订单状态文本
const orderStatusText = computed(() => {
  const statusMap = {
    unpaid: '待付款',
    unshipped: '待发货',
    unreceived: '待收货',
    completed: '已完成',
    cancelled: '已取消'
  };
  return statusMap[orderInfo.value.status] || '';
});

// 订单状态描述
const orderStatusDesc = computed(() => {
  const descMap = {
    unpaid: '请尽快完成支付',
    unshipped: '商家正在处理订单',
    unreceived: '商品正在配送中',
    completed: '交易已完成',
    cancelled: '订单已取消'
  };
  return descMap[orderInfo.value.status] || '';
});

// 获取订单详情
const getOrderDetail = async (orderId) => {
  try {
    const res = await uni.$api.order.getOrderDetail(orderId);
    if (res.success) {
      orderInfo.value = res.data;
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    uni.showToast({
      title: '获取订单详情失败',
      icon: 'none'
    });
  }
};

// 支付订单
const payOrder = async () => {
  try {
    uni.showLoading({
      title: '准备支付...'
    });

    const res = await payService.payOrder(orderInfo.value.orderNo, {
      amount: orderInfo.value.payAmount * 100, // 转换为分
      total_fee: orderInfo.value.payAmount * 100, // 添加 total_fee 参数，微信支付JSAPI必需
      description: `订单${orderInfo.value.orderNo}支付`,
      paymentMethod: 'WXPAY'
    });
    
    console.log('支付接口响应:', res);

    // 根据实际的响应结构判断是否成功
    const isSuccess = res.code === 0 || res.success === true;
    const paymentData = res.data;

    if (!isSuccess || !paymentData) {
      throw new Error(res.message || '创建支付失败');
    }

    uni.hideLoading();

    // 检查支付参数
    if (!paymentData.timeStamp || !paymentData.nonceStr || !paymentData.package || !paymentData.paySign) {
      console.error('支付参数不完整:', paymentData);
      throw new Error('支付参数不完整，请重试');
    }

    // 调用微信支付
    await uni.requestPayment({
      timeStamp: paymentData.timeStamp,
      nonceStr: paymentData.nonceStr,
      package: paymentData.package,
      signType: paymentData.signType || 'MD5',
      paySign: paymentData.paySign,
      success: (payRes) => {
        console.log('支付成功:', payRes);
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        });
        
        // 延迟刷新订单详情
        setTimeout(() => {
          getOrderDetail(orderInfo.value.id);
        }, 1000);
      },
      fail: (err) => {
        console.error('支付失败或取消:', err);
        
        if (err.errMsg && err.errMsg.includes('cancel')) {
          uni.showToast({
            title: '支付已取消',
            icon: 'none'
          });
        } else {
          uni.showToast({
            title: '支付失败',
            icon: 'none'
          });
        }
      }
    });
    
  } catch (error) {
    console.error('支付处理失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: error.message || '支付失败',
      icon: 'none'
    });
  }
};

// 取消订单
const cancelOrder = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await uni.$api.order.cancelOrder(orderInfo.value.id);
          if (res.success) {
            uni.showToast({
              title: '取消成功',
              icon: 'success'
            });
            getOrderDetail(orderInfo.value.id);
          }
        } catch (error) {
          console.error('取消订单失败:', error);
          uni.showToast({
            title: '取消失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 确认收货
const confirmReceive = () => {
  uni.showModal({
    title: '提示',
    content: '确认已收到商品？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await uni.$api.order.confirmOrder(orderInfo.value.id);
          if (res.success) {
            uni.showToast({
              title: '确认成功',
              icon: 'success'
            });
            getOrderDetail(orderInfo.value.id);
          }
        } catch (error) {
          console.error('确认收货失败:', error);
          uni.showToast({
            title: '确认失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 删除订单
const deleteOrder = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await uni.$api.order.deleteOrder(orderInfo.value.id);
          if (res.success) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            uni.navigateBack();
          }
        } catch (error) {
          console.error('删除订单失败:', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 查看物流
const viewLogistics = () => {
  uni.navigateTo({
    url: `/pages/order/logistics?orderId=${orderInfo.value.id}`
  });
};

// 再次购买
const buyAgain = () => {
  // 将商品添加到购物车
  orderInfo.value.items.forEach(async (item) => {
    try {
      await uni.$api.cart.addToCart({
        skuId: item.skuId,
        quantity: item.quantity
      });
    } catch (error) {
      console.error('添加购物车失败:', error);
    }
  });
  
  // 跳转到购物车页面
  uni.switchTab({
    url: '/pages/cart/cart'
  });
};

// 跳转到商品详情
const navToGoodsDetail = (spuId) => {
  uni.navigateTo({
    url: `/pages/goods/detail?spuId=${spuId}`
  });
};

// 页面加载
onLoad((options) => {
  if (options.orderId) {
    getOrderDetail(options.orderId);
  }
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.status-section {
  background-color: #ff4444;
  padding: 40rpx 30rpx;
  color: #fff;
  
  .status-box {
    .status {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      display: block;
    }
    
    .desc {
      font-size: 26rpx;
      opacity: 0.9;
    }
  }
}

.address-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .user {
    margin-bottom: 10rpx;
    
    .name {
      font-size: 30rpx;
      margin-right: 20rpx;
    }
    
    .phone {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .address {
    font-size: 26rpx;
    color: #333;
    line-height: 1.4;
  }
}

.goods-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  
  .goods-item {
    display: flex;
    padding: 20rpx;
    border-bottom: 2rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .goods-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
    }
    
    .goods-info {
      flex: 1;
      margin-left: 20rpx;
      
      .goods-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .goods-specs {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
      }
      
      .price-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price {
          font-size: 32rpx;
          color: #ff4444;
          font-weight: bold;
        }
        
        .count {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
  }
}

.order-section {
  background-color: #fff;
  padding: 0 30rpx;
  
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    border-bottom: 2rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .value {
      color: #666;
    }
    
    .price {
      color: #ff4444;
    }
    
    &.total {
      padding: 30rpx 0;
      
      .price {
        font-size: 36rpx;
        font-weight: bold;
      }
    }
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .btn {
    width: 180rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    border-radius: 35rpx;
    font-size: 28rpx;
    margin-left: 20rpx;
    
    &.outline {
      border: 2rpx solid #999;
      color: #666;
    }
    
    &.primary {
      background-color: #ff4444;
      color: #fff;
    }
  }
}
</style> 